<?php

namespace App\Services\Coin;

use ccxt\binance;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class BinancePriceService
{
    private $symbols;
    private $instance_ccxt;

    public function __construct()
    {
        $this->symbols = config('user.symbols');
        $this->instance_ccxt = new binance();
    }

    public static function keyPrice($symbol)
    {
        return 'binance:' . trim($symbol);
    }

    public function putPrice($symbol, $price_latest = 0)
    {
        Cache::put(self::keyPrice($symbol), $price_latest);
    }

    public function getPrice($symbol)
    {
        return Cache::get(self::keyPrice($symbol)) ?: 1;
    }

    public function storeLatest()
    {
        foreach ($this->symbols as $symbol => $cfg) {
            try {
                throw_if(!isset($cfg['pair']), new \Exception("config.pair expected"));
                $price = $this->instance_ccxt->fetch_ticker($cfg['pair']);
            } catch (\Exception $e) {
                $this->logger()->warning("BinancePriceService.fetch_ticker({$cfg['pair']}) failed, " . $e->getMessage());
            }

            $this->putPrice($symbol, $price['last'] ?? 0);
        }

        $this->logger()->info("BinancePriceService.storeLatest done");
    }

    public function toValue($symbol)
    {
        return $this->getPrice($symbol);
    }

    protected function logger(){
        return Log::channel('profit');
    }

}
